<?php

namespace App\Logging\Service;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Route;
use Ramsey\Uuid\Uuid;

class LogGeneralService
{
    const PATH_MODE_GENERAL = 'general';
    const PATH_MODE_CONTROLLER = 'controller';
    const PATH_MODE_API = 'api';

    /**
     * @var static 单例模式
     */
    protected static $instance;

    /**
     * 单例模式
     */
    public static function getInstance()
    {
        if (static::$instance instanceof static) {
            return static::$instance;
        }
        static::$instance = new static();
        return static::$instance;
    }

    /**
     * 基于模式生成命令日志子目录
     * @param $mode
     * @return string
     * @author Chris Yu <chrisyu@crabapple.top> 2024/11/8
     */
    public function generateLogSubDir($mode): string
    {
        if ($mode === self::PATH_MODE_CONTROLLER) {
            return $this->generateLogSubDirBaseController();
        }
        elseif ($mode === self::PATH_MODE_API) {
            return $this->generateLogSubDirBaseApi();
        }
        return '';
    }

    /**
     * 生成子目录-基于控制器
     * 控制器需要进入 controller 类才能获取
     * @return string
     * @author Chris Yu <chrisyu@crabapple.top> 2024/11/8
     */
    protected function generateLogSubDirBaseController()
    {
        if (App::runningInConsole()) {
            return '';
        }

        // 获取控制器和方法的完整名称
        $action = Route::currentRouteName();
        if (!$action) {
            return '';
        }
        // 获取控制器名称
        $controller = class_basename(explode('@', $action)[0]);
        // 获取方法名称
        $method = explode('@', $action)[1];

        return $controller . '/' . $method;
    }

    /**
     * 生成子目录-基于 api 名称
     * @return string
     * @author Chris Yu <chrisyu@crabapple.top> 2024/11/8
     */
    protected function generateLogSubDirBaseApi()
    {
        if (App::runningInConsole()) {
            return '';
        }

        return request()->path();
    }
}
